package com.atguigu.yygh.oss.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.atguigu.yygh.oss.service.FileService;
import com.atguigu.yygh.oss.util.ConstantOssPropertiesUtils;
import org.joda.time.DateTime;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.UUID;

/**
 * @author:ahang
 * @create:2022-09-08 18:55
 * @Description:
 */
@Service
public class FileServiceImpl implements FileService {

    @Override
    public String uplode(MultipartFile file) {
        String endpoint = "https://" + ConstantOssPropertiesUtils.END_POINT;

        String accessKeyId = ConstantOssPropertiesUtils.ACCESS_KEY_ID;
        String accessKeySecret = ConstantOssPropertiesUtils.ACCESS_KEY_SECRET;
        String bucketName = ConstantOssPropertiesUtils.BUCKET_NAME;

        DateTime dateTime = new DateTime();
        String dateString = dateTime.toString("yyyy/MM/dd");
        String filename = file.getOriginalFilename();
        String objectName = dateString + "/"+ UUID.randomUUID().toString().replaceAll("-","") +filename;


        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

        try {
//            String filePath= "D:\\qiniu\\1.png";
//            InputStream inputStream = new FileInputStream(filePath);
            InputStream inputStream = file.getInputStream();

            // 创建PutObject请求。
            ossClient.putObject(bucketName, objectName, inputStream);
        } catch (Exception oe) {

        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
        return "https://"+ ConstantOssPropertiesUtils.BUCKET_NAME+"."+ConstantOssPropertiesUtils.END_POINT+"/" + objectName;
    }
}
